<?php
/**
 * About Model
 *
 * @property About $about
 */
class About extends AdminAppModel 
{

    public $useTable = 'abouts';

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';

    public function getAboutData()
    {
        return $this->findById(1);
    }


    public function saveAboutData($req, $originData)
    {
        $req = $req['About'];
        // upload about_banner
        $bannerImg = $this->_uploadBannerImg($req, $originData);

        $data = array(
            'About' => array(
                'about_desc' => $req['about_desc'],
                'about_banner' => $bannerImg,
                'updated' => time()
            )
        );
        $this->id = $req['id'];
        if (!$this->save($data)) {
            throw new Exception("The data could not be saved.");
        }
    }

    /**
     * 处理标题的图片logo
     * @param array $requestData 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    private function _uploadBannerImg($requestData, $orginData=array())
    {
        $orginImage = $orginData['About']['about_banner'];
        $uploadFile = $this->upload($requestData['about_banner'], 'banner_img_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

    protected function upload($data, $prefix, $exception='upload fail')
    {
        if ($data['size'] == 0) {
            return '';
        }
        if (is_uploaded_file($data['tmp_name'])) {
            $folder = 'uploads/'.date('Ymd');
            if (!is_dir($folder)) {
                mkdir($folder);
            }
            $pathinfo = pathinfo($data['name']);
            $extension = $pathinfo['extension'];
            $filename = uniqid($prefix).'.'.$extension;
            $path = $folder.'/'.$filename;
            if (move_uploaded_file($data['tmp_name'], $path)) {
                return $path;
            }
        }
        throw new Exception($exception);

    }

}
